import picture from '@/assets/img/hover-effect.jpg';
import { BoxStyle } from './style';
import { useEffect, useRef } from 'react';

const yRange: [number, number] = [-15, 15];
const xRange: [number, number] = [-15, 15];

function getRotate(range: [number, number], value: number, max: number) {
	return Math.floor((value / max) * (range[1] - range[0]) + range[0]);
}

const HoverEffect = () => {
	const CardRef = useRef<HTMLDivElement>();

	useEffect(() => {
		CardRef.current.onmousemove = (e) => {
			const { offsetX, offsetY } = e;
			const { offsetWidth, offsetHeight } = CardRef.current;
			const ry = -getRotate(xRange, offsetX, offsetWidth);
			const rx = getRotate(yRange, offsetY, offsetHeight);
			CardRef.current.style.setProperty('--rx', `${rx}deg`);
			CardRef.current.style.setProperty('--ry', `${ry}deg`);
		};
		CardRef.current.onmouseleave = () => {
			CardRef.current.style.setProperty('--rx', '0deg');
			CardRef.current.style.setProperty('--ry', '0deg');
		};
	}, []);

	return (
		<BoxStyle>
			<div className="card" ref={CardRef}>
				<img className="rick" src={picture} alt="rick" />
			</div>
		</BoxStyle>
	);
};

export default HoverEffect;
